import http from './request'

class ApiService {

  constructor() {
    // 单例模式实现
    if (ApiService.instance) {
      return ApiService.instance
    }
    
    this.appKey = "9101fca7a5471bb6"
    this.sign = "OTU0Y2M5NzIwNzgwYzM4OGMwMjk1Nzc2NmIwZjUzZjk4NzEyNTFlYjg3YzA3MjIzNWVhZjEwMzJlYTE2Zjc5Zg=="
    
    // 预制的常用请求参数
    this.baseParams = {
      appKey: this.appKey,
      sign: this.sign
    }
    
    ApiService.instance = this
  }

  // 工作表ID枚举定义
  static WORKSHEETENUM = {
    PROJECTS: '6876257b872d9db2c7ba529a',
    DEMAND: '6876257b872d9db2c7ba5292',
    CANDIDATE: '6876257b872d9db2c7ba5297',
    USER: '6886e6ba427a9931f8180b01',
    // 可以继续添加更多工作表ID
  }


  async register({
    worksheetId,
    controls,
    triggerWorkflow = false 
  } = {}) {
    try {
      const requestData = {
        ...this.baseParams,
        worksheetId: worksheetId,
        controls: controls,
        triggerWorkflow: triggerWorkflow
      }

      const res = await http.post('/addRow', requestData, {
        timeout: 6000 // 单行数据使用更短超时
      })
      return res
    } catch (error) {
      console.error('【register】注册失败，错误详情:', {
        message: error.message,
        stack: error.stack,
        error: error
      })
      
      throw error
    }
  }



  async quotation(data) {
    try {
      const res = await http.withEndpoint('workflow').post('/NjhhNTJiODkzNTZlNjA1ZWYzMTdlNDMw', data)
      return res
    } catch (error) {
      console.error('【register】注册失败，错误详情:', {
        message: error.message,
        error: error
      })
  
      throw error
    }
  }



  async getUserInfo(data) {
    try {
      const requestData = {
        ...this.baseParams,
        worksheetId: "6886e6ba427a9931f8180b01",
        viewId: "",
        notGetTotal: "true",
        filters:[
          {
          "controlId": "rowid",
          "dataType": 2,
          "spliceType": 1,
          "filterType": 2,
          "value": data
        }
        ]
      }

      const res = await http.post('/getFilterRows', requestData, {
        timeout: 6000 // 单行数据使用更短超时
      })
      return res
    } catch (error) {
      console.error('【register】getUserInfo失败，错误详情:', {
        message: error.message,
        stack: error.stack,
        error: error
      })
      
      throw error
    }
  }

  async getRowsData({
    worksheetId,
    notGetTotal = true,
    filters = []
  } = {}) {
    try {
      const requestData = {
        ...this.baseParams,
        worksheetId: worksheetId,
        viewId: "",
        notGetTotal,
        filters
      }

      const res = await http.post('/getFilterRows', requestData, {
        timeout: 6000 // 单行数据使用更短超时
      })
      return res
    } catch (error) {
      console.error('getRowsData失败，错误详情:', {
        message: error.message,
        stack: error.stack,
        error: error
      })
      
      throw error
    }
  }


// async getUserInfo(data) {
//   console.log('getUserInfo');
//   console.log(data);
  
//   try {
//     const res = await http.withEndpoint('workflow').post('/NjhiNTg3NjgyZGQ4OTQzZWFhOTViY2E3', data)
//     return res
//   } catch (error) {
//     console.error('getStatus:', {
//       message: error.message,
//       error: error
//     })

//     throw error
//   }
// }
  
async getCeshi(data) {
  console.log('getCeshi');
  console.log(data);
  
  try {
    const res = await http.withEndpoint('workflow').post('/NjhiNTYwN2UyZGQ4OTQzZWFhOTJlZTE4', data)
    return res
  } catch (error) {
    console.error('getStatus:', {
      message: error.message,
      error: error
    })

    throw error
  }
}

  
async upload(data) {
  console.log('upload');
  console.log(data);
  
  try {
    const res = await http.withEndpoint('workflow').post('/NjhiMTUwYzY4MjMxNGY3M2U5MGY5ZGFh', data)
    return res
  } catch (error) {
    console.error('upload:', {
      message: error.message,
      error: error
    })

    throw error
  }
}


  async getRoleList(data) {
    console.log('getRoleList');
    console.log(data);
    
    try {
      const res = await http.withEndpoint('workflow').post('/NjhiMTM5OTM4MjMxNGY3M2U5MGYxNmMz', data)
      return res
    } catch (error) {
      console.error('getStatus:', {
        message: error.message,
        error: error
      })
  
      throw error
    }
  }

  async getProjectStatus(data) {
    try {
      const res = await http.withEndpoint('workflow').post('/NjhiNjVlMDRkNGZhOTM2ZGUwMTE0MzU1', data)
      console.log('getProjectStatus返回结果');
      console.log(res);
      return res
    } catch (error) {
      console.error('getProjectStatus:', {
        message: error.message,
        error: error
      })
  
      throw error
    }
  }

  async updateUserInfo(data) {
    console.log('updateUserInfo');
    console.log(data);
    
    try {
      const res = await http.withEndpoint('workflow').post('/NjhiN2JmYWNkZGE0MTI2NGYwZjIzMzQx', data)
      return res
    } catch (error) {
      console.error('updateUserInfo:', {
        message: error.message,
        error: error
      })
  
      throw error
    }
  }

  async getStatus(data) {
    console.log('getStatus');
    console.log(data);
    
    try {
      const res = await http.withEndpoint('workflow').post('/NjhiMDFhN2MyNGMzNjExM2I3M2JiMmIz', data)
      return res
    } catch (error) {
      console.error('getStatus:', {
        message: error.message,
        error: error
      })
  
      throw error
    }
  }


  /**
   * 上传单个文件
   * @param {string} filePath - 文件路径
   * @param {Object} formData - 额外的表单数据
   * @param {Object} options - 上传选项（如进度回调等）
   * @returns {Promise} 返回上传结果
   */
  async uploadSingleFile(filePath, formData = {}, options = {}) {
    try {
      console.log('开始上传文件:', filePath);
      
      // 使用 uni.uploadFile 上传文件
      return new Promise((resolve, reject) => {
        const uploadTask = uni.uploadFile({
          url: 'https://baiyumei.oss-cn-hangzhou.aliyuncs.com', // 文件上传专用接口
          filePath: filePath,
          name: 'file',
          formData: {
            ...formData,
            appKey: this.appKey,
            sign: this.sign,
            timestamp: Date.now()
          },
          timeout: 60000, // 60秒超时
          success: (res) => {
            try {
              console.log('文件上传响应:', res);
              const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
              
              if (res.statusCode === 200) {
                // 返回文件URL，支持多种响应格式
                const fileUrl = data.url || data.fileUrl || data.data?.url || data.data?.fileUrl;
                if (fileUrl) {
                  resolve({ url: fileUrl, ...data });
                } else {
                  console.warn('上传成功但未返回文件URL:', data);
                  resolve(data);
                }
              } else {
                const errorMessage = data.message || data.msg || '上传失败';
                uni.showToast({
                  title: errorMessage,
                  icon: 'none'
                });
                reject(new Error(errorMessage));
              }
            } catch (error) {
              console.error('解析上传响应失败:', error);
              reject(new Error('上传响应解析失败'));
            }
          },
          fail: (error) => {
            console.error('文件上传失败:', error);
            uni.showToast({
              title: error.errMsg || '文件上传失败',
              icon: 'none'
            });
            reject(new Error(error.errMsg || '文件上传失败'));
          }
        });
        
        // 添加上传进度监听
        if (options.onProgress && typeof options.onProgress === 'function') {
          uploadTask.onProgressUpdate(options.onProgress);
        }
        
        // 添加默认进度显示
        uploadTask.onProgressUpdate((res) => {
          console.log('上传进度:', res.progress + '%');
          if (res.progress === 100) {
            console.log('文件上传完成，等待服务器处理...');
          }
        });
      });
    } catch (error) {
      console.error('【uploadSingleFile】上传文件失败:', error);
      throw error;
    }
  }

  /**
   * 批量上传文件
   * @param {Array} filePaths - 文件路径数组
   * @param {Object} baseFormData - 基础表单数据
   * @returns {Promise} 返回所有文件的上传结果
   */
  async uploadMultipleFiles(filePaths, baseFormData = {}) {
    try {
      const uploadPromises = filePaths.map((filePath, index) => 
        this.uploadSingleFile(filePath, {
          ...baseFormData,
          fileIndex: index
        })
      );
      
      const results = await Promise.all(uploadPromises);
      return results;
    } catch (error) {
      console.error('【uploadMultipleFiles】批量上传文件失败:', error);
      throw error;
    }
  }


  
  async submitRecommend(data) {
    try {
      const res = await http.withEndpoint('workflow').post('/NjhhNmRmMzllYTA3YWMyZGEwZTg5MGQ1', data)
      return res
    } catch (error) {
      console.error('【register】注册失败，错误详情:', {
        message: error.message,
        stack: error.stack,
        error: error
      })
  
      throw error
    }
  }

  /**
   * 获取筛选行数据 - 优化版本
   * @param {string} worksheetId - 工作表ID
   * @param {boolean} notGetTotal - 是否不获取总数
   * @param {Array} filters - 筛选条件
   * @returns {Promise} 返回数据Promise
   */
  async getFilterRows({
    worksheetId,
    pageIndex = 1,
    pageSize = 20,
    notGetTotal = true,
    filters = [],
    useCache = true // 新增：是否使用缓存
  } = {}) {

    try {
      const requestData = {
        ...this.baseParams,
        worksheetId: worksheetId,
        viewId: "",
        pageIndex: pageIndex,
        pageSize: pageSize,
        notGetTotal: notGetTotal,
        filters: filters
      }

      // 对于首页数据，使用较短的超时时间
      const options = {
        timeout: pageIndex === 1 ? 8000 : 10000
      }

      const res = await http.post('/getFilterRows', requestData, options)
      return res
    } catch (error) {
      console.error('获取筛选行数据失败:', error)
      
      // 提供更友好的错误提示
      const errorMessage = this.getErrorMessage(error)
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 2000
      })
      
      throw error
    }
  }

  /**
   * 根据ID获取行数据 - 优化版本
   * @param {string} rowId - 行ID
   * @param {string} worksheetId - 工作表ID
   * @param {boolean} getSystemControl - 是否获取系统控件
   * @returns {Promise} 返回数据Promise
   */
  async getRowById({
    rowId,
    worksheetId,
    getSystemControl = false
  } = {}) {
    try {
      const requestData = {
        ...this.baseParams,
        worksheetId: worksheetId,
        rowId: rowId,
        getSystemControl: getSystemControl
      }

      const res = await http.post('/getRowByIdPost', requestData, {
        timeout: 6000 // 单行数据获取使用更短超时
      })
      return res
    } catch (error) {
      console.error('根据ID获取行数据失败:', error)
      
      const errorMessage = this.getErrorMessage(error)
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 2000
      })
      
      throw error
    }
  }

  /**
   * 批量预加载数据
   * @param {Array} requests - 请求配置数组
   */
  async preloadData(requests = []) {
    const preloadPromises = requests.map(config => {
      if (config.type === 'getFilterRows') {
        return http.preload('/getFilterRows', {
          ...this.baseParams,
          ...config.params
        }, 'POST')
      } else if (config.type === 'getRowById') {
        return http.preload('/getRowByIdPost', {
          ...this.baseParams,
          ...config.params
        }, 'POST')
      }
    })

    try {
      await Promise.allSettled(preloadPromises)
      console.log('数据预加载完成')
    } catch (error) {
      console.log('预加载失败，但不影响正常使用:', error)
    }
  }

  /**
   * 快速获取候选人数据（带优化）
   */
  async getCandidatesQuick(options = {}) {
    const defaultOptions = {
      worksheetId: ApiService.WORKSHEETENUM.CANDIDATE,
      pageIndex: 1,
      pageSize: 10, // 首次加载较少数据，提高速度
      notGetTotal: false,
      ...options
    }

    return this.getFilterRows(defaultOptions)
  }

  /**
   * 快速获取项目数据（带优化）
   */
  async getProjectsQuick(options = {}) {
    const defaultOptions = {
      worksheetId: ApiService.WORKSHEETENUM.PROJECTS,
      pageIndex: 1,
      pageSize: 10,
      notGetTotal: false,
      ...options
    }

    return this.getFilterRows(defaultOptions)
  }

  /**
   * 获取友好的错误信息
   * @param {Error} error - 错误对象
   * @returns {string} 友好的错误信息
   */
  getErrorMessage(error) {
    if (error.message?.includes('timeout')) {
      return '网络超时，请检查网络连接'
    } else if (error.message?.includes('Network Error')) {
      return '网络连接失败，请重试'
    } else if (error.message?.includes('401')) {
      return '登录已过期，请重新登录'
    } else if (error.message?.includes('500')) {
      return '服务器异常，请稍后重试'
    } else {
      return error.message || '请求失败，请重试'
    }
  }

  /**
   * 清除相关缓存
   * @param {string} worksheetId - 工作表ID
   */
  clearWorksheetCache(worksheetId) {
    http.clearCache(worksheetId)
  }

  /**
   * 清除所有API缓存
   */
  clearAllCache() {
    http.clearCache()
  }
}

// 创建并导出单例实例，保持向后兼容
const apiService = new ApiService()

// 同时导出类实例，方便新功能使用
export { apiService, ApiService }
